from datetime import datetime
from app import db
import json


class MatchmakingRecord(db.Model):
    """牵线记录模型"""
    __tablename__ = 'matchmaking_records'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, comment='申请用户ID')
    target_user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, comment='目标用户ID')
    matchmaker_id = db.Column(db.Integer, db.ForeignKey('matchmakers.id', ondelete='SET NULL'), comment='红娘ID')
    status = db.Column(db.Integer, default=1, comment='状态：1待处理2进行中3成功4失败5已取消')
    commission_amount = db.Column(db.Numeric(10, 2), default=20.00, comment='佣金金额')
    commission_status = db.Column(db.Integer, default=1, comment='佣金状态：1待发放2已发放3已取消')
    apply_message = db.Column(db.Text, comment='申请留言')
    matchmaker_note = db.Column(db.Text, comment='红娘备注')
    result_message = db.Column(db.Text, comment='结果反馈')
    contact_info = db.Column(db.Text, comment='联系方式信息')
    success_time = db.Column(db.DateTime, comment='成功时间')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 索引
    __table_args__ = (
        db.Index('idx_user_id', 'user_id'),
        db.Index('idx_target_user_id', 'target_user_id'),
        db.Index('idx_matchmaker_id', 'matchmaker_id'),
        db.Index('idx_status', 'status'),
        db.Index('idx_commission_status', 'commission_status'),
    )

    def __repr__(self):
        return f'<MatchmakingRecord {self.id}>'

    def to_dict(self):
        """转换为字典"""
        contact_info_dict = {}
        if self.contact_info:
            try:
                contact_info_dict = json.loads(self.contact_info)
            except:
                contact_info_dict = {}

        return {
            'id': self.id,
            'user_id': self.user_id,
            'target_user_id': self.target_user_id,
            'matchmaker_id': self.matchmaker_id,
            'status': self.status,
            'status_text': self._get_status_text(),
            'commission_amount': float(self.commission_amount) if self.commission_amount else 20.00,
            'commission_status': self.commission_status,
            'commission_status_text': self._get_commission_status_text(),
            'apply_message': self.apply_message,
            'matchmaker_note': self.matchmaker_note,
            'result_message': self.result_message,
            'contact_info': contact_info_dict,
            'success_time': self.success_time.strftime('%Y-%m-%d %H:%M:%S') if self.success_time else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    def _get_status_text(self):
        """获取状态文本"""
        status_map = {
            1: '待处理',
            2: '进行中',
            3: '成功',
            4: '失败',
            5: '已取消'
        }
        return status_map.get(self.status, '未知')
    
    def _get_commission_status_text(self):
        """获取佣金状态文本"""
        status_map = {
            1: '待发放',
            2: '已发放',
            3: '已取消'
        }
        return status_map.get(self.commission_status, '未知') 